<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import {
  ElButton,
  ElMessage,
  ElMessageBox,
  ElDialog,
  ElTable,
  ElTableColumn,
  ElInput,
  ElPopover
} from 'element-plus'

import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { storageType } from '@/api/common/types'
import {
  storageIndex,
  storageDEL,
  goodsSelect,
  placestartSelect,
  storageSubmit,
  storageAudit,
  enterRk,
  purchase_refundAdd,
  getRepertoryList,
  multiCreateDeliver,
  rkdExportExcel
} from '@/api/common'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { ref, reactive, unref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useRouter } from 'vue-router'
//权限
import { useAppStoreWithOut } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'

const { t } = useI18n()

defineOptions({
  name: 'WarehousingEntry'
})
const { wsCache } = useCache()
const appStore = useAppStoreWithOut()
const userRlues = wsCache.get(appStore.getUserInfo).rlues //权限数组
const userId = wsCache.get(appStore.getUserInfo).id

const checkRlues = (rlues) => {
  //检查权限
  if (userRlues.includes(rlues)) {
    return true
  } else {
    ElMessage.error('当前用户无权限操作，请联系管理员')
    return false
  }
}

const { push, replace } = useRouter()

const { register, tableObject, methods, elTableRef } = useTable<storageType>({
  getListApi: storageIndex,
  delListApi: storageDEL,
  response: {
    list: 'data',
    total: 'total'
  },
  defaultParams: {
    filter: '{"status":"2"}',
    op: '{"status":"<"}'
  },
  find: userRlues.includes('201') ? -1 : userId
})

const { getList, setSearchParams } = methods

const { emitter } = useEmitt()

getList()

useEmitt({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      tableObject.currentPage = 1
    }
    getList()
  }
})

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'entertime_text',
    label: '入库时间',
    table: {
      width: '150px'
    },
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'out_date',
    label: '出库日期',
    table: {
      width: '150px'
    },
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'delivery_date',
    label: t('warehousingEntry.receivingDate'),
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        type: 'date'
      }
    },
    form: {
      show: false,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'placestart',
    label: t('warehousingEntry.origin'),
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await placestartSelect({})
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'placeend',
    label: t('warehousingEntry.destination'),
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await placestartSelect({})
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'client_code',
    label: '客户号',
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'shouhuo',
    label: t('purchaseOrderAddWrite.recipient'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'remark',
    label: t('warehousingEntry.productNameRemarks'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'piece',
    label: '件数',
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'goods_id',
    label: t('warehousingEntry.typeOfGoods'),
    table: {
      show: false
    },
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await goodsSelect({})
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      show: false,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: false
    }
  },
  {
    field: 'goods_text',
    label: t('warehousingEntry.typeOfGoods'),
    search: {
      show: false
    },
    form: {
      show: false
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'box_num',
    label: '装箱数',
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'short_fee_cny',
    label: '短途运费',
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'imitate',
    label: '是否仿牌',
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'id',
    label: t('warehousingEntry.number'),
    search: {
      show: false
    },
    form: {
      show: false,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'status_text',
    label: '状态',
    search: {
      show: false
    },
    form: {
      show: false,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },

  // {
  //   field: 'store_id',
  //   label: t('warehousingEntry.locationOfGoods'),
  //   table: {
  //     show: false
  //   },
  //   search: {
  //     show: true,
  //     component: 'Select',
  //     api: async () => {
  //       const res: any = await storeSelect({})
  //       let list: any = []
  //       res.data.list.forEach((item) => {
  //         list.push({
  //           label: item.name,
  //           value: item.id
  //         })
  //       })
  //       return list
  //     },
  //     componentProps: {
  //       filterable: true,
  //       options: []
  //     }
  //   },
  //   form: {
  //     show: false,
  //     colProps: {
  //       span: 24
  //     }
  //   },
  //   detail: {
  //     span: 24,
  //     show: false
  //   }
  // },
  // {
  //   field: 'store_text',
  //   label: t('warehousingEntry.locationOfGoods'),
  //   search: {
  //     show: false,
  //     component: 'Select',
  //     api: async () => {
  //       const res: any = await storeSelect({})
  //       let list: any = []
  //       res.data.list.forEach((item) => {
  //         list.push({
  //           label: item.name,
  //           value: item.id
  //         })
  //       })
  //       return list
  //     },
  //     componentProps: {
  //       filterable: true,
  //       options: []
  //     }
  //   },
  //   form: {
  //     show: false,
  //     colProps: {
  //       span: 24
  //     }
  //   },
  //   detail: {
  //     span: 24,
  //     show: true
  //   }
  // },
  // {
  //   field: 'transport',
  //   label: t('warehousingEntry.modeOfTransport'),
  //   search: {
  //     show: true,
  //     component: 'Select',
  //     api: async () => {
  //       const res: any = await transportSelect({})
  //       let list: any = []
  //       res.data.list.forEach((item) => {
  //         list.push({
  //           label: item.name,
  //           value: item.id
  //         })
  //       })
  //       return list
  //     },
  //     componentProps: {
  //       filterable: true,
  //       options: []
  //     }
  //   },
  //   form: {
  //     colProps: {
  //       span: 24
  //     }
  //   },
  //   detail: {
  //     span: 24,
  //     show: true
  //   }
  // },

  {
    field: 'taxrate',
    label: t('shippingOrderSettings.taxRate'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },

  {
    field: 'paytype_text',
    label: t('rebateUsers.paymentTypes'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },

  {
    field: 'action',
    width: '80px',
    label: t('formDemo.operate'),
    form: {
      show: false
    },
    fixed: 'right',
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const AddAction = (rlues) => {
  if (checkRlues(rlues)) push('/logistics/warehousingEntryAdd')
}

const mulitExport = async (rlues) => {
  if (checkRlues(rlues)) {
    const { getSelections } = methods
    const selections = await getSelections()
    let num = -1
    for (let i = 0; i < unref(elTableRef)?.getSelectionRows().length; i++) {
      let item = unref(elTableRef)?.getSelectionRows()[i]
      if (item.status != 1) {
        console.log('---item.id---', item.status)
        ElMessage.error('有未提交的数据，无法转出库单，请先提交数据')
        break
      }
      num = i
    }
    if (num == unref(elTableRef)?.getSelectionRows().length - 1) {
      let res = await multiCreateDeliver({
        ids: getArr(selections).substring(0, getArr(selections).length - 1)
      })
      console.log('---批量转出库单---', res)
      ElMessage.success('操作成功')
      unref(elTableRef)?.clearSelection()
    }
  }
}

const rkdExport = async (rlues) => {
  if (checkRlues(rlues)) {
    let res = await rkdExportExcel(null)
    console.log('---导出入库单---', res)
    const date = new Date()
    var Y = date.getFullYear()
    var M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    const href = URL.createObjectURL(res.data)
    const box = document.createElement('a')
    box.download = `${Y}-${M}-${D}入库单.xls`
    box.href = href
    box.click()
  }
}

const delLoading = ref(false)
const getArr = (selections) => {
  let a = ''
  selections.map((v) => (a += v.id + ','))
  return a
}

const delData = async (row: storageType | null, multiple: boolean, rlues: string) => {
  if (!checkRlues(rlues)) {
    return false
  }
  tableObject.currentRow = row
  const { delList, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delList(
    multiple ? getArr(selections) : (tableObject.currentRow?.id as string),
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}

const getRepertoryListFn = async (id) => {
  tkTableData.value = []
  let res = await getRepertoryList({
    storage_id: id
  })
  // console.log('---入库货物数据---', id, res)
  res.data.length > 0 &&
    res.data.forEach((item: any) => {
      item.amount = 0
      item.count = 0
      tkTableData.value.push(item)
    })
}

const tkShow = ref(false)
const enterShow = ref(false)
const enterId = ref()
let enterTableData: any = reactive([])
const storageId = ref(0)
const tkTableData: any = ref([
  // {
  //   name: '大葱',
  //   number: 100,
  //   price: 0.1,
  //   tkNumber: '',
  //   tkPrice: 0
  // }
])
const numInput = (ev, index) => {
  if (ev > tkTableData.value[index].total) {
    tkTableData.value[index].count = tkTableData.value[index].total
  }
  tkTableData.value[index].amount =
    Number(ev > tkTableData.value[index].total ? tkTableData.value[index].total : ev) *
    Number(tkTableData.value[index].worth)
}
const action = async (row: storageType, type: string, rlus: string) => {
  if (!checkRlues(rlus)) {
    return false
  }
  switch (type) {
    case 'Edit':
      {
        push(`/logistics/warehousingEntry${type}?id=${row.id}`)
      }
      break
    case 'enter':
      // let res = await getClientRepertoryList({
      //   storage_id: row.id,
      //   pageSize: 10000,
      //   page: 1
      // })
      // console.log('----查询需要一件入库的数据----', res)
      console.log(row.goods, 'row')
      enterTableData = JSON.parse(row.goods)
      let goodsStr = row.goods.replace(/&quot;/g, '"')
      enterTableData = JSON.parse(goodsStr)
      enterTableData.forEach((item, index) => {
        item.success = Number(item.success ? item.success : 0)
        item.lrNumber = 0
        item.needNum =
          Number(item.piece ? item.piece : 1) * Number(item.quantity) -
          Number(item.success ? item.success : 0)
        item.needTotal = Number(item.piece ? item.piece : 1) * Number(item.quantity)
      })
      enterId.value = row.id
      enterShow.value = true
      break
    case 'submitForReview':
      {
        ElMessageBox.confirm(
          `是否${t('warehousingEntry.submitForReview')}?`,
          t('common.delWarning'),
          {
            confirmButtonText: t('common.delOk'),
            cancelButtonText: t('common.delCancel'),
            type: 'warning'
          }
        ).then(async () => {
          const res = await storageSubmit('' + row.id)
          if (res) {
            ElMessage.success('提交成功')
            emitter.emit('getList', 'edit')
          }
        })
      }
      break
    case 'confirmReview':
      {
        ElMessageBox.confirm(
          `是否${t('warehousingEntry.confirmReview')}?`,
          t('common.delWarning'),
          {
            confirmButtonText: t('common.delOk'),
            cancelButtonText: t('common.delCancel'),
            type: 'warning'
          }
        ).then(async () => {
          const res = await storageAudit('' + row.id)
          if (res) {
            ElMessage.success('提交成功')
            emitter.emit('getList', 'edit')
          }
        })
      }
      break
    case 'detail':
      {
        push(`/logistics/warehousingEntryEdit?id=${row.id}&isDetail=true`)
      }
      break
    case 'refund':
      {
        await getRepertoryListFn(row.id)
        storageId.value = Number(row.store_id)
        tkShow.value = true
        // let goodsStr = row.goods.replace(/&quot;/g, '"')
        // let goodsArr: any = JSON.parse(goodsStr)
        // console.log('---需要生成退货单的数据---', goodsArr)
        // let goods: any = [
        //   {
        //     id: 0,
        //     count: 0,
        //     amount: 0
        //   }
        // ]
        // ElMessageBox.confirm(`是否生成退货单`, t('common.delWarning'), {
        //   confirmButtonText: t('common.delOk'),
        //   cancelButtonText: t('common.delCancel'),
        //   type: 'warning'
        // }).then(async () => {
        //   const res = await purchase_refundAdd({
        //     storage_id: row.client_code,
        //     goods: goods
        //   })
        //   if (res) {
        //     ElMessage.success('提交成功')
        //     emitter.emit('getList', 'edit')
        //   }
        // })
      }
      break
    default:
      break
  }
}

const confirmEnter = async () => {
  let data: any = {
    ids: enterId.value,
    total: []
  }
  enterTableData.forEach((item) => {
    data.total.push(Number(item.lrNumber))
  })
  console.log(data)
  const res = await enterRk(data)
  if (res) {
    ElMessage.success('提交成功')
    emitter.emit('getList', 'edit')
    enterShow.value = false
  }
}
const confirmTk = () => {
  let goods: any = []
  tkTableData.value.forEach((item) => {
    goods.push({
      id: item.id,
      amount: item.amount,
      count: item.count
    })
  })
  tkShow.value = false
  ElMessageBox.confirm(`是否生成退货单`, t('common.delWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  }).then(async () => {
    const res = await purchase_refundAdd({
      storage_id: storageId.value,
      goods: goods
    })
    if (res) {
      ElMessage.success('提交成功')
      emitter.emit('getList', 'edit')
    }
  })
}

const testPush = () => {
  // push({ path: '/logistics/invoice', replace: true })
  replace('/logistics/invoice')
}
</script>

<template>
  <ContentWrap>
    <Search
      :model="{}"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <ElButton type="primary" @click="rkdExport('23-1')">导出入库单</ElButton>
      <ElButton type="primary" @click="mulitExport('23-1')">批量转出库单</ElButton>
      <ElButton type="primary" @click="AddAction('23-1')">{{ t('exampleDemo.add') }}</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData(null, true, '23-3')">
        {{ t('exampleDemo.del') }}
      </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.limit"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElPopover placement="right" :width="80" trigger="click">
          <template #reference>
            <ElButton type="primary"> ··· </ElButton>
          </template>
          <div class="btnContent"
            ><ElButton
              type="primary"
              v-if="row.status == 0"
              @click="action(row, 'submitForReview', '23-2')"
            >
              {{ t('warehousingEntry.submitForReview') }}
            </ElButton>
            <ElButton
              type="warning"
              v-if="row.status == 1"
              @click="action(row, 'confirmReview', '23-5')"
            >
              {{ t('warehousingEntry.confirmReview') }}
            </ElButton>
            <ElButton type="warning" v-if="row.status == 2" @click="action(row, 'refund', '24-5')">
              {{ t('common.generateReturnOrder') }}
            </ElButton>
            <ElButton type="warning" v-if="row.status == 2" @click="action(row, 'enter', '24-5')">
              一键入库
            </ElButton>
            <ElButton type="primary" v-if="row.status <= 1" @click="action(row, 'Edit', '23-2')">
              {{ t('exampleDemo.edit') }}
            </ElButton>
            <ElButton type="primary" v-if="row.status == 5" @click="action(row, 'Edit', '23-2')">
              {{ t('common.refund') }}
            </ElButton>
            <ElButton type="success" @click="action(row, 'detail', '23-4')">
              {{ t('router.watch') }}
            </ElButton>
            <ElButton type="danger" @click="delData(row, false, '23-3')">
              {{ t('exampleDemo.del') }}
            </ElButton></div
          >
        </ElPopover>
      </template>
    </Table>

    <ElDialog title="填写退款信息" v-model="tkShow">
      <div class="tkTable">
        <ElTable :data="tkTableData" stripe style="width: 100%">
          <ElTableColumn prop="goods_text" label="名称" />
          <ElTableColumn prop="total" label="数量" />
          <ElTableColumn prop="worth" label="单价" />
          <ElTableColumn prop="count" label="退款数量">
            <template #default="scope">
              <ElInput
                v-model="scope.row.count"
                @input="
                  (ev) => {
                    numInput(ev, scope.$index)
                  }
                "
              />
            </template>
          </ElTableColumn>
          <ElTableColumn prop="amount" label="退款金额">
            <template #default="scope">
              <ElInput v-model="scope.row.amount" disabled />
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <!-- <el-button @click="tkSho = false">Cancel</el-button> -->
          <ElButton @click="tkShow = false">取消</ElButton>
          <ElButton type="primary" @click="confirmTk"> 确认 </ElButton>
        </span>
      </template>
    </ElDialog>
    <ElDialog title="一键入库" v-model="enterShow">
      <div class="tkTable">
        <ElTable :data="enterTableData" stripe style="width: 100%">
          <ElTableColumn prop="gname" label="名称" />
          <ElTableColumn prop="piece" label="件数" />
          <ElTableColumn prop="quantity" label="装箱数" />
          <ElTableColumn prop="needTotal" label="需入库数量" />
          <ElTableColumn prop="success" label="已入库数量" />
          <ElTableColumn prop="needNum" label="需填补数量" />
          <ElTableColumn prop="lrNumber" label="实际入库总数量">
            <template #default="scope">
              <ElInput :disabled="scope.row.needNum == 0" v-model="scope.row.lrNumber" />
            </template>
          </ElTableColumn>
        </ElTable>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <!-- <el-button @click="tkSho = false">Cancel</el-button> -->
          <ElButton @click="enterShow = false">取消</ElButton>
          <ElButton type="primary" @click="confirmEnter"> 确认 </ElButton>
        </span>
      </template>
    </ElDialog>
  </ContentWrap>
</template>
<style lang="less" scoped>
.btnContent {
  display: flex;
  flex-direction: column;
  :deep .el-button + .el-button {
    margin-left: 0;
    margin-top: 15px;
  }
}
</style>
